package com.qd.panda.service.stroke.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.stroke.UserStrokeOrderRefundDTO;
import com.qd.panda.mapper.stroke.UserStrokeOrderRefundMapper;
import com.qd.panda.model.UserStrokeOrderRefund;
import com.qd.panda.service.stroke.BigDecimalUtil;
import com.qd.panda.service.stroke.DisplayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 退款信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeOrderRefundService extends BaseService<UserStrokeOrderRefundMapper, UserStrokeOrderRefund> {

    private static final String ORDER_ID = "order_id";
    private static final String PREFIX_ID = "panda_user_stroke_order_refund_refundId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_USER_BID_AND_REFUND_NO = "panda_user_stroke_order_refund_bid_{0}_refundNo_{1}";

    private final RedisTemplateUtil<UserStrokeOrderRefund> redisTemplateUtil;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderRefundDTO save(UserStrokeOrderRefundDTO dto) {
        checkUnique(dto);
        final UserStrokeOrderRefund model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderRefundDTO update(UserStrokeOrderRefundDTO dto) {
        checkUnique(dto);
        final UserStrokeOrderRefund historyModel = Optional.ofNullable(getById(dto.getRefundId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStrokeOrderRefund model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(model);
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param refundId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String refundId) {
        final UserStrokeOrderRefund model = Optional.ofNullable(getById(refundId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(refundId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeOrderRefundDTO dto) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param refundId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String refundId) {
        boolean exists = false;
        if (StringUtils.hasLength(refundId)) {
            final UserStrokeOrderRefund model = getById(refundId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param refundId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderRefund getById(String refundId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, refundId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(refundId), UserStrokeOrderRefund.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param refundId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderRefundDTO getByIdDto(String refundId) {
        return Optional.ofNullable(getById(refundId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderRefund getOne(UserStrokeOrderRefundDTO dto) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = createQueryWrapper(dto);
        UserStrokeOrderRefund model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderRefundDTO getOneDto(UserStrokeOrderRefundDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderRefund> getList(UserStrokeOrderRefundDTO dto) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = createQueryWrapper(dto);
        final List<UserStrokeOrderRefund> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderRefundDTO> getListDto(UserStrokeOrderRefundDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeOrderRefundDTO> page(Page<UserStrokeOrderRefund> page, UserStrokeOrderRefundDTO dto) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = createQueryWrapper(dto, "use.");
        final IPage<UserStrokeOrderRefundDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }


    /**
     * 根据唯一性索引获得数据
     * <p>
     * param bid
     * param refundNo
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderRefund getUniqueByBidAndRefundNo(String bid, Integer refundNo) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bid", bid);
        queryWrapper.eq("refund_no", refundNo);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER_BID_AND_REFUND_NO, bid, refundNo);
        final UserStrokeOrderRefund model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), UserStrokeOrderRefund.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(UserStrokeOrderRefundDTO dto) {
        UserStrokeOrderRefund model = getUniqueByBidAndRefundNo(dto.getOrderId(), dto.getRefundNo());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(UserStrokeOrderRefundDTO dto, UserStrokeOrderRefund model) {
        if (!StringUtils.hasLength(dto.getRefundId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getRefundId().equals(model.getRefundId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStrokeOrderRefund model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getRefundId());
        redisTemplateUtil.deleteByKey(key);
        key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER_BID_AND_REFUND_NO, model.getOrderId(), model.getRefundNo());
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeOrderRefundDTO modelToDto(UserStrokeOrderRefund model) {
        if (null == model) {
            return null;
        }
        final UserStrokeOrderRefundDTO dto = new UserStrokeOrderRefundDTO();
        dto.setRefundId(model.getRefundId());
        dto.setPayAmount(model.getPayAmount());
        dto.setRefundAmount(model.getRefundAmount());
        dto.setRefundTime(model.getRefundTime());
        dto.setRefundStatus(model.getRefundStatus());
        dto.setRefundNo(model.getRefundNo());
        dto.setOrderId(model.getOrderId());
        dto.setSid(model.getSid());
        dto.setBid(model.getBid());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStrokeOrderRefund dtoToModel(UserStrokeOrderRefundDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStrokeOrderRefund model = new UserStrokeOrderRefund();
        model.setRefundId(dto.getRefundId());
        model.setPayAmount(dto.getPayAmount());
        model.setRefundAmount(dto.getRefundAmount());
        model.setRefundTime(dto.getRefundTime());
        model.setRefundStatus(dto.getRefundStatus());
        model.setRefundNo(dto.getRefundNo());
        model.setOrderId(dto.getOrderId());
        model.setSid(dto.getSid());
        model.setBid(dto.getBid());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeOrderRefundDTO dto) {
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setRefundAmountDisplay(Optional.ofNullable(dto.getRefundAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setRefundStatusDisplay(DisplayUtil.getRefundStatusDisplay(dto.getRefundStatus()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeOrderRefundDTO> modelToDtoList(List<UserStrokeOrderRefund> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStrokeOrderRefund> dtoToModelList(List<UserStrokeOrderRefundDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStrokeOrderRefund> createQueryWrapper(UserStrokeOrderRefundDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStrokeOrderRefund> createQueryWrapper(UserStrokeOrderRefundDTO dto, String tableAlias) {
        final QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getOrderId())) {
                queryWrapper.eq(tableAlias + ORDER_ID, dto.getOrderId());
            }
            if (StringUtils.hasLength(dto.getBid())) {
                queryWrapper.eq(tableAlias + "bid", dto.getBid());
            }
            if (StringUtils.hasLength(dto.getSid())) {
                queryWrapper.eq(tableAlias + "sid", dto.getSid());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<UserStrokeOrderRefund> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStrokeOrderRefund> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStrokeOrderRefund::getRefundId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public List<UserStrokeOrderRefundDTO> getListDTO(String orderId) {
        return modelToDtoList(getList(orderId));
    }

    /**
     * 获得退款订单
     *
     * @param orderId 支付订单ID
     * @return 退款订单列表
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderRefund> getList(String orderId) {
        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ORDER_ID, orderId);
        queryWrapper.in("refund_status", DisplayUtil.REFUND_STATUS_0, DisplayUtil.REFUND_STATUS_1);
        queryWrapper.orderByAsc("refund_time");
        final List<UserStrokeOrderRefund> list = super.getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 获得退款订单
     *
     * @param orderId 支付订单ID
     * @param flag    0表示实际优惠1用于对账
     * @return 退款订单列表
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderRefundDTO> getOrderRefundListByOrderId(String orderId, Integer flag) {
        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ORDER_ID, orderId);
        if (null != flag) {
            queryWrapper.eq("flag", flag);
        }
        queryWrapper.orderByAsc("refund_time");
        final List<UserStrokeOrderRefund> list = super.getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        return modelToDtoList(list);
    }

//    /**
//     * 获得退款成功的订单
//     * @param orderId 支付订单ID
//     * @return 退款订单列表
//     */
//    @Transactional(readOnly = true)
//    public List<UserStrokeOrderRefund> getOkList(String orderId) {
//        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("order_id",orderId);
//        queryWrapper.in("refund_status",DisplayUtil.REFUND_STATUS_1);
//        queryWrapper.orderByAsc("refund_time");
//        final List<UserStrokeOrderRefund> list = super.getBaseMapper().selectList(queryWrapper);
//        queryWrapper.clear();
//        return list;
//    }

    /**
     * 查询编号的最大值
     *
     * @param bid 业务ID
     * @return 最大值
     */
    @Transactional(readOnly = true)
    public Integer getMaxNumber(String bid) {
        Integer num = Optional.ofNullable(getBaseMapper().getMaxNumber(bid)).orElse(0);
        return num + 1;
    }

    /**
     * 是否存在正在进行中的退款
     *
     * @param sid          行程ID
     * @param bid          业务ID
     * @param refundAmount 退款金额
     * @return true or false
     */
    @Transactional(readOnly = true)
    public boolean isExistProcess(String sid, String bid, BigDecimal refundAmount) {
        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", sid);
        queryWrapper.eq("bid", bid);
        queryWrapper.eq("refund_amount", refundAmount);
        //0就是没有收到回执，算进行中 1表示成功。这两种情况不能申请，如果是失败，可以继续申请
        queryWrapper.in("refund_status", DisplayUtil.REFUND_STATUS_0, DisplayUtil.REFUND_STATUS_1);
        boolean exists = super.baseMapper.exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }

    /**
     * 是否存在正在进行中的退款
     *
     * @param bid          业务ID
     * @param refundAmount 退款金额
     * @return true or false
     */
    @Transactional(readOnly = true)
    public boolean isExistProcess(String bid, BigDecimal refundAmount) {
        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bid", bid);
        queryWrapper.eq("refund_no", 1);
        queryWrapper.eq("refund_amount", refundAmount);
        //0就是没有收到回执，算进行中 1表示成功。这两种情况不能申请，如果是失败，可以继续申请
        queryWrapper.in("refund_status", DisplayUtil.REFUND_STATUS_0, DisplayUtil.REFUND_STATUS_1);
        boolean exists = super.baseMapper.exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }

    /**
     * 查询退款金额
     *
     * @param orderId 订单编号
     * @return 退款金额
     */
    @Transactional(readOnly = true)
    public BigDecimal refundAmountByOrderId(String orderId) {
        QueryWrapper<UserStrokeOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("refund_status", DisplayUtil.REFUND_STATUS_1);
        queryWrapper.select("sum(refund_amount) as refundAmount");
        UserStrokeOrderRefund userStrokeOrderRefund = super.getOne(queryWrapper, false);
        if (null == userStrokeOrderRefund) {
            return null;
        } else {
            return userStrokeOrderRefund.getRefundAmount();
        }
    }
}